/*
 * This servlet controls the manage courseview for Teachers and Administrators
 *
 */
package controllers.managecontrollers;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Category;
import models.Course;
import models.Employee;
import models.User;
import dao.CategoryDao;
import dao.CourseDao;
import classes.HibernateUtil;
import org.hibernate.Session;

/**
 *
 * @author Achie
 */
public class ManageCourseViewController extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HibernateUtil hu = new HibernateUtil();
        Session ses = hu.openSession();

        //Load current courses        
        CourseDao cd = new CourseDao(ses);
        List<Course> courselist = cd.findAll();
        hu.close();
        //prepare courses
        ArrayList<Course> teachersCourses = new ArrayList<Course>();
        HttpSession overallSession = request.getSession();

        if (overallSession.getAttribute("userrole") == null) {
            response.sendRedirect("jsp/index.jsp");
            return;
        }

        if (overallSession.getAttribute("userrole").equals("Teacher")) { //get the courses ONLY from the teacher/admin
            grabTeacherCourses(request, response);
        } else if (overallSession.getAttribute("userrole").equals("Administrator")) { //get all the courses
            grabAdministratorCourses(request, response);
        } else { //its a student, redirect him to the index.
            response.sendRedirect("jsp/index.jsp");
        }
    }

    public void grabTeacherCourses(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HibernateUtil hu = new HibernateUtil();
        CourseDao cd = new CourseDao(hu.openSession());
        CategoryDao catdao = new CategoryDao(hu.openSession());
        List<Category> categorylist = catdao.findAll();
        List<Course> courselist = cd.findAll();
        hu.close();
        
        ArrayList<Course> teachersCourses = new ArrayList<Course>();
        HttpSession overallSession = request.getSession();
        User loggedInUser = (User) overallSession.getAttribute("user");//get logged in user id
        long id = loggedInUser.getMember_id();
        
        for (int i = 0; i < courselist.size(); i++) {//grab courses from this id
            Set<Employee> temp = courselist.get(i).getTeacher(); //teacher list from the course
            List<Employee> list = new ArrayList<Employee>(temp); //convert temp to list
            
            for (int p = 0; p < list.size(); p++) {
                if (list.get(p).getId() == id) { //if true, the current logged in employee is found as teacher in the course
                    teachersCourses.add(courselist.get(i));//assign course to the list;
                }
            }
            
        }
        //get categories from the course
        request.setAttribute("categorylist", categorylist);
        request.setAttribute("courselist", teachersCourses);

        RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/manage_courses.jsp");
        dispatcher.forward(request, response);
    }

    public void grabAdministratorCourses(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HibernateUtil hu = new HibernateUtil();
        CategoryDao cate = new CategoryDao(hu.openSession());
        List<Category> categorylist = cate.findAll();
        CourseDao cd = new CourseDao(hu.openSession());
        List<Course> courselist = cd.findAll();
        hu.close();        
        request.setAttribute("categorylist", categorylist); //prepare categories
        request.setAttribute("courselist", courselist);

        RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/manage_courses.jsp");
        dispatcher.forward(request, response);
    }

    //I dont know if I will use this method or if it will become handy one day... please leave it alone.
    public List<Category> getRequiredCategories(ArrayList<Course> coursesFromTeacher) {
        HibernateUtil hu = new HibernateUtil();
        CategoryDao cd = new CategoryDao(hu.openSession());
        List<Category> categories = cd.findAll();
        hu.close();
        ArrayList<Category> required_categories = new ArrayList<Category>();

        for (int i = 0; i < coursesFromTeacher.size(); i++) {
            for (int p = 0; p < categories.size(); p++) {
                Category cat = coursesFromTeacher.get(i).getCategory(); //category in the course 
                if (categories.get(p).getId() == cat.getId()) {

                    required_categories.add(categories.get(p));
                }

            }
        }

        return required_categories;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //check if its a sort        
        if (request.getParameter("sort").equals("sort")) {
            HttpSession overallSession = request.getSession();
            if (overallSession.getAttribute("userrole").equals("Administrator")) { //if its the admin who wants to sort
                long id = Long.parseLong(request.getParameter("categorysort"));
                HibernateUtil hu = new HibernateUtil();
                CourseDao cd = new CourseDao(hu.openSession());
                CategoryDao dd = new CategoryDao(hu.openSession());

                //make empty course list
                ArrayList<Course> coursefromcategory = new ArrayList<Course>();
                List<Course> course = cd.findAll();                

                for (int i = 0; i < course.size(); i++) { //pick every course with the correct category
                    if (course.get(i).getCategory().getId() == id) { //found a course with the chosen category
                        coursefromcategory.add(course.get(i));
                    }
                }

                request.setAttribute("courselist", coursefromcategory);
                //get categories set in request
                request.setAttribute("categorylist", dd.findAll());
                
                hu.close();
                RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/manage_courses.jsp");
                dispatcher.forward(request, response);
                
            } else if (overallSession.getAttribute("userrole").equals("Teacher")) { // if its the teacher who wants to sort
                long catid = Long.parseLong(request.getParameter("categorysort"));

                HibernateUtil hu = new HibernateUtil();
                CourseDao cd = new CourseDao(hu.openSession());
                CategoryDao dd = new CategoryDao(hu.openSession());
                List<Course> courselist = cd.findAll();
                ArrayList<Course> teachersCourses = new ArrayList<Course>();
                ArrayList<Category> cattemp = new ArrayList<Category>();

                User loggedInUser = (User) overallSession.getAttribute("user");//get logged in user id
                long id = loggedInUser.getMember_id();
                for (int i = 0; i < courselist.size(); i++) {//grab courses from this id
                    Set<Employee> temp = courselist.get(i).getTeacher(); //teacher list from the course
                    List<Employee> list = new ArrayList<Employee>(temp); //convert temp to list
                    for (int p = 0; p < list.size(); p++) {
                        if (list.get(p).getId() == id && courselist.get(i).getCategory().getId() == catid) { //if true, the current logged in employee is found as teacher in the course
                            teachersCourses.add(courselist.get(i));//assign course to the list;
                        }
                    }
                }

                request.setAttribute("courselist", teachersCourses);
                //get categories set in request
                request.setAttribute("categorylist", dd.findAll());
                hu.close();
                
                RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/manage_courses.jsp");
                dispatcher.forward(request, response);
            }

        }
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
